/**
 * ColorPicker module
 */

import eventHelper from "../../../utils/EventHelper";
import React, {Component} from 'react';
import { connect } from 'dva';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import pagesActions from '../../../actions/Editor/pages';
import editorActions from '../../../actions/Editor/editor';
import tool from "../../../utils/tool";
import consts from "../../../consts/consts";
import storage from "../../../utils/storage";
import colorPickerProvider from "../../provider/colorPickerProvider";
// var dataProvider = require("../provider/dataProvider");
// var historyProvider = require("../provider/historyProvider");
import Validator from "../../../utils/validator/Validator";
// var autoSaveProvider = require("../provider/autoSaveProvider");

// var WidgetPropertyCommand = require("../command/WidgetPropertyCommand");
class ColorPicker extends Component {
    getInitialProps(){
        return {
            root: {},
            widget: {},
            parent: {}
        }
    }
    initElements(){
        this.elements = {
            colorpicker: $(this.refs.colorpicker)
        };
    }
    componentWillMount(){
        var widget = this.props.widget;
        this.storeData = $.extend(true, {}, widget);
    }
    componentDidMount(){
        let me = this;
        this.initElements();
        this.elements.colorpicker.one('focus', function (){
            new colorPickerProvider(me.elements.colorpicker, function (color){
                const {widget,parent} = me.props;
                if(widget){
                    me.updateColor(color);
                } else me.updatePageColor(color);
                
            });
        });
    }
    handleOnChangeColor(type, color){
        const {selectedWidgetId,widget,parent,updateWidget} = this.props;
        if (widget){
            this.updateColor(color);
        } else if(parent) {
            this.updatePageColor(color);
        }
    }
    updatePageColor(color){
        const {page,updatePage} = this.props;
        const {page_background} = page || {};
        page_background['backgroundColor'] = color;
        let param = {
            page_background: page_background,
            page_id: page.page_id
        };
        updatePage(param);
    }
    handleOnPropertyUpdate(){
        const {widget,parent,setState,updateWidget} = this.props;
        // 页面
        if (parent){
            this.updatePageColor(this.streData.color);
        // 元件
        } else {
            var type = "color";
            if (this.checkInputVaild(type, widget.color, true)){
                this.updateWidget(widget);
                eventHelper.trigger(consts.EVENTS.THREED_WIDGET_PROPERTY_CHANGED, this.storeData);
            } else {
                this.updateWidget(this.storeData);
            }
        }
    }
    updateColor(color){
        const {widget,selectedWidgetId,updateWidget,setState} = this.props;
        let data = widget;
        data.color = color;
        setState({selectedWidget: data})
        updateWidget(data);
    }
    updateInputColor(e){
        const {widget: data} = this.props;
        var input = $(e.target);
        var val = input.val();

        var type = "color";
        if (data){
            if (this.checkInputVaild(type, val, false)){
                this.updateColor(val);
            }
        } else {
            this.updatePageColor(val);
        }
    }
    updateWidget(data){
        const {updateWidget,setState} = this.props;
        setState({selectedWidget: data});
        updateWidget(data);
    }
    checkInputVaild(type, value, needAlert){
        var validator = Validator();

        validator.addRule(value, [{ validator: "empty", error: "颜色值不能为空" }, { validator: type }]);

        var errors = validator.execute();
        errors && needAlert && alert(errors);

        return !errors;
    }
    render(){
        const {widget,parent}= this.props;
        let data = widget;
        if (!widget){
            data = {
                color: parent.props.page.page_background.backgroundColor
            }
        }
        console.log(data.color)
        return (
            <div className="rowlist">
                <label className="pull-left">{$._("Color")}</label>
                <input onBlur={() => this.handleOnPropertyUpdate()} ref="colorpicker" name="color" type="text" className="colordiv form-control" readOnly maxLength="6" size="6" style={{background: "#" + data.color, color: "#" + data.color}} data-colorpicker="F70454 8CFF05 03DDFF FFCD00 8C00FF" />
                <input onBlur={() => this.handleOnPropertyUpdate()} onChange={(e) => this.updateInputColor(e)} name="color" type="text" className="widget-color form-control" maxLength="6" size="6" value={data.color} />
                <div className='color-presets'>
                    <div name="color" onClick={() => this.handleOnChangeColor("color", "6ABB4F")} data-color="6ABB4F" className="color-preset 6ABB4F" style={{backgroundColor: "#6ABB4F"}}></div>
                    <div name="color" onClick={() => this.handleOnChangeColor("color", "419BF9")} data-color="419BF9" className="color-preset 419BF9" style={{backgroundColor: "#419BF9"}}></div>
                    <div name="color" onClick={() => this.handleOnChangeColor("color", "FA648C")} data-color="FA648C" className="color-preset FA648C" style={{backgroundColor: "#FA648C"}}></div>
                    <div name="color" onClick={() => this.handleOnChangeColor("color", "F8E71C")} data-color="F8E71C" className="color-preset F8E71C" style={{backgroundColor: "#F8E71C"}}></div>
                    <div name="color" onClick={() => this.handleOnChangeColor("color", "50C3E2")} data-color="50C3E2" className="color-preset 50C3E2" style={{backgroundColor: "#50C3E2"}}></div>
                </div>
            </div>
        )
    }
 }

 const mapStateToProps = ({ editor, pages, widgets }) => {
    const pageId = editor.selectedPageId;
    return {
      page: pages.filter(p => p.page_id === pageId)[0],
      selectedWidgetId: editor.selectedWidgetId,
      widgets: widgets.filter(w => w.page_id === pageId),
    };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...pagesActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(ColorPicker);
